#!/usr/bin/perl
#http://sourceforge.net/projects/csv2xml/forums/forum/422301/topic/1179362
# Copyright(c) Fred P. 2004
# Released under the artistic license or LGPL license.
# 10-17-2012 Tim Bergsma.  Modified and released under same.

#usage: perl csv2xml.pl < test.csv
#usage: perl csv2xml.pl  test.csv
use strict;

sub getFields($){
  $_ = $_[0];
  chomp;
  my @chars = split('',$_);
  my @tokens = ();
  push @tokens, '';
  tokenize(\@tokens, \@chars,',');
  return @tokens;
}

sub pushChar($$){
  my $arrayref = shift;
  my $char = shift;
  my $len = scalar(@$arrayref);
  $$arrayref[$len -1] = $$arrayref[$len -1] . $char;
  return 1;
}

sub tokenize($$$){
  my $tokenref = shift;
  my $charref = shift;
  my $delimiter = shift;
  return 1 unless(@$charref);
  my $char = shift @$charref;
  if ($delimiter eq ','){
    if ($char eq $delimiter) {push @$tokenref, ''}	  
    elsif ($char=~/['"]/)    {$delimiter = $char}
    else                     {pushChar($tokenref, $char)}
  }else{
    if ($char eq $delimiter) {$delimiter = ','}
    else                     {pushChar($tokenref, $char)}
  } 	  
  tokenize($tokenref,$charref,$delimiter);
}

sub toXML($){
  $_ = $_[0];
  s/&/&amp;/g;
  s/</&lt;/g;
  s/>/&gt;/g;
  #s/'/&apos;/g;
  #s/"/"/g;
  # More XML character entity...
  # http://www.w3schools.com/html/html_entitiesref.asp
  return $_;
}


sub getAllFields(){
  my @file = <>;
  my @fields = ();
  for my $i ( 0 .. $#file ){
    my @field = getFields($file[$i]);
    push @fields, \@field;
  }
  return @fields;
}

sub fileToXmlContent(){
  my $row      = "row";
  my $spacy    = "  ";   
  my $head_row = "<".$row.">\n";
  my $foot_row = "</".$row.">\n";
  my @fields   = getAllFields();
  my @names    = @{ $fields[0] };
  my $content  = "";
  my @head_tag = ();
  my @foot_tag = ();
  for my $i ( 0 .. $#names ){
    #10-15-2012 Tim Bergsma
    unless($names[$i]){$names[$i]='undefined';}
    $names[$i]=~s/,/./g;
    $names[$i]=~s/[^\w-:.]/_/g;
    $head_tag[$i] = $spacy . "<". $names[$i] .">";
    $foot_tag[$i] = "</". $names[$i] .">\n";
  }
  for my $j ( 1 .. $#fields ){
    my @val   = @{ $fields[$j] };
    $content .= $head_row;
    for my $k ( 0 .. $#val ){
      $content .= $head_tag[$k];
      $content .= toXML($val[$k]);
      $content .= $foot_tag[$k];
    }
    $content .= $foot_row;
  }
  $content = "<table>\n" . $content . "</table>\n";
  return $content;
}

sub main(){
  print fileToXmlContent();
  exit;
}

main;
exit;
1;
